package idv.kikka.server.handler;

import idv.kikka.server.common.R;
import idv.kikka.server.service.factories.ChatGroupServiceFactory;
import idv.kikka.common.message.GroupChatRequestMessage;
import idv.kikka.common.message.GroupChatResponseMessage;
import idv.kikka.server.service.ChatGroupService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
@ChannelHandler.Sharable
@Slf4j
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        //获取群聊中每个成员的channel
        ChatGroupService chatGroupService= ChatGroupServiceFactory.getChatGroupService();
        R<List<Channel>> result = chatGroupService.getMembersChannel(msg.getGroupName());
        if(result.getCode()!=1){
            ctx.writeAndFlush(new GroupChatResponseMessage(false, result.getMsg()));
        }
        else {
            List<Channel> membersChannel = result.getData();
            for (Channel channel : membersChannel) {
                //给群聊中每个成员发送信息
                channel.writeAndFlush(new GroupChatResponseMessage(msg.getFrom(), msg.getContent()));
            }
        }
    }
}
